﻿
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using RBAC.Domain;
using RBAC.Repository;

namespace Sowrk03_28.Repository
{
    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private readonly MyDbContext _dbcontext;

        public Repository(MyDbContext dbcontext)
        {
            _dbcontext = dbcontext;
        }

        public async Task<List<T>> AllAsync()
        {
            return await _dbcontext.Set<T>().ToListAsync();
        }

        public async Task<int> CreateAsync(T entity)
        {
            var dbSet = _dbcontext.Set<T>();
            dbSet.AddAsync(entity);
            return await _dbcontext.SaveChangesAsync();
        }

        public async Task<List<T>> GetValues(Expression<Func<T, bool>> expre)
        {
            var info = await _dbcontext.Set<T>().Where(expre).ToListAsync();
            return  info;
        }

        public async Task<int> DeleteAsync(T entity)
        {
            _dbcontext.Remove(entity);
            return await _dbcontext.SaveChangesAsync();
        }

        public async Task<T> GetAsync(int id)
        {
            var dbSet = _dbcontext.Set<T>();
            return await dbSet.FindAsync(id);
        }

        public async Task<int> UpdateAsync(T entity)
        {
            _dbcontext.Update(entity);
            return await _dbcontext.SaveChangesAsync();
        }

        public async Task<int> DeleteAllAsync(List<T> t)
        {
            _dbcontext.RemoveRange(t);
            return await _dbcontext.SaveChangesAsync();
        }
    }
}
